<template>
	<view>
		<uni-drawer @jihuo="jihuo" :user_money="userinfo['user_money']" :malock="ma_lock" :memu="memu" :foxtel="userinfo['user_name']" :visible="showLeft" mode="left" @close="closeDrawer('left')"></uni-drawer>
		<!-- 顶部菜单 star-->				
		<view class="is-nav">
			<view class="is-nav-li is-nav-user" @click="show('left')">
				<image src="../../static/img/common/user.png" mode=""></image>
			</view>
			<view class="is-nav-li is-center is-grey" @tap="tohome">
				OTC接单			
			</view>
			<view class="is-nav-li is-center is-blue is-active">
				进行中
			</view>
			<view class="is-nav-li is-size-14 is-online" :class="[online === false ? 'is-red-color is-bold' : 'is-blue']">
				{{online === false ? '离线' : '在线'}}
			</view>
		</view>			
		<!-- 顶部菜单 end -->
		<view class="bg-f">
			<view v-show="listok == 1" class="has-pd-20 s-row ma-order" v-for="(item,index) in listorder" :key="index">
				<view class="is-col-5 is-left ma-box">
					<image :src="item.ma_type_img" mode=""></image>
				</view>
				<view class="is-col-14">
					<view class="is-bold">{{item.order_no}}</view>
					<view class="is-grey">￥{{item.total_fee_true}}</view>
				</view>
				<view class="is-col-5 is-right">
					<button type="primary" class="is-btn" @tap="grabinfo(item.id)">详情</button>
				</view>
			</view>
		</view>
		<!-- 没有订单 star-->
		<view v-show="listok == 0" class="is-no-order">
			<view class="no-order-ico"><image src="../../static/img/common/none.png" mode=""></image></view>
			<view class="is-grey"><text>您当前没有进行中的订单哦~</text></view>
			<view class="is-blue" @tap="toorder"><text>去抢单</text></view>
		</view>
		<!-- 没有订单 end-->
		<view>
		    <show-modal></show-modal>
		</view>
	</view>
</template>
<script>
	var _self;
	var lordertime = null;
	import uniDrawer from '@/components/uni-drawer/uni-drawer.vue'
	export default {
		components: {
			uniDrawer,
		},
		data() {
			return {
				showLeft: false,
				showRight: false,
				foxtoken:'',
				foxcode:'',
				foxactive:'',
				memu:[],
				userinfo:[],
				user_money_can:0,
				fox_money_can:0,
				fox_user_jihuo:0,
				online:true,
				ma_lock:0,
				socketTask: null,
				// 确保websocket是打开状态
				is_open_socket: false,
				listorder:[],
				listok:0,
				uid:0,
				user_tel:'',
				ma_type_img:'',
			}
		},
		onLoad() {	
			_self = this;
			let info = this.service.getfox();
			if(info[0]){
				//console.log(info[0])				
				this.foxtoken = info[0]['foxtoken'];
				//uni.clearStorageSync();
				uni.request({
					url: this.service.FOX_URL + 'diamond/get_userinfo_home',
					method:'POST',
					data: {
						user_key: this.foxtoken
					},
					dataType:'json',
					header:{
						'content-type':'application/x-www-form-urlencoded',
					},
					success: res => {
						// var rest = JSON.stringify(res);
						// console.log(res)
						var rest = res.data;
						if(rest.status == 'success'){
							this.userinfo = rest.msg;
							this.ma_lock = this.userinfo['ma_lock'];
							this.uid= this.userinfo['user_id'];
							this.user_tel= this.userinfo['user_name'];
							this.fox_money_can = this.userinfo['diamondset']['diamond_money_can'];
							this.fox_user_jihuo = this.userinfo['diamondset']['diamond_user_jihuo'];
							//console.log(this.userinfo)
						}else if(rest.status == 'error'){
							uni.showToast({
								title:rest.msg,
								icon:'none',
								mask:true
							})
						}else{
							uni.showToast({
								title:rest.msg,
								icon:'none',
								mask:true
							})
						}
					}
				})
			}else{
				uni.reLaunch({
					url:'../logon/login'
				})
			}
			this.memu = this.service.memu;
			this.connectSocketInit();
		},
		// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			this.closeSocket();
		},
		computed: {
			neworder() {
				return this.listorder
			}
		},
		watch:{
			neworder: {
				handler: (val, olVal) => {
					let a = Object.keys(val).length;
					let b = Object.keys(olVal).length;
					let music = uni.getStorageSync('music');
					if(b==0 && a >0){
						if(music === true){
							_self.OrdernewAudio();
						}
					}else if(b>0 && a >0){
						if(JSON.stringify(val) !== JSON.stringify(olVal)){
							if(music === true){
								_self.OrdernewAudio();
							}
						}
					}
				},
				deep: true
			},
			'online':function(){
				this.LineAuto(this.online);
			}
		},
		methods: {
			show(e) {
				if (e === 'left') {
					this.showLeft = true
				}
			},
			closeDrawer(e) {
				if (e === 'left') {
					this.showLeft = false
				}
			},
			// 进入这个页面的时候创建websocket连接【整个页面随时使用】
			connectSocketInit() {
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: this.service.FOX_SOKET,
					success(data) {
						console.log("websocket连接成功");
					},
				});
			 
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					this.online = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					
					lordertime = setInterval(()=>{
						let message = {'type':'listorder','user_key':this.foxtoken};
						this.socketTask.send({
							data: JSON.stringify(message),
							async success() {
								console.log("listorder消息发送成功");
							},
						});
					},5000)
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log("收到服务器内容listorder");
						var rest = JSON.parse(res.data);
						// console.log(rest)
						if(rest.type == 'listorder'){
							if(rest.data.list.length >0){
								this.listorder = rest.data.list;
								this.listok = 1;
								// console.log(this.listorder)
							}else{
								this.listok = 0;
							}
						}
						// let rets = JSON.stringify(this.listorder);
						// console.log(rets)
					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				// this.socketTask.onClose(() => {
				// 	_self.online = false;
				// })
				// this.socketTask.onError(function(){
				// 	_self.online = false;
				// })
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
					}
				})
			},
			jihuo(){
				this.$showModal({
				    title: '提示',
				    content: '激活帐号需扣除'+this.fox_user_jihuo+'DC，激活成功可进行接单',
					cancelText:'拒绝',
					confirmText:'同意',
				    success: function (res) {
				        if (res.confirm) {
				            uni.request({
				            	url: _self.service.FOX_URL + 'diamond/jihuo_user',
				            	method:'POST',
				            	data: {
				            		user_key: _self.foxtoken
				            	},
				            	dataType:'json',
				            	header:{
				            		'content-type':'application/x-www-form-urlencoded',
				            	},
				            	success: res => {
				            		// var rest = JSON.stringify(res);
				            		// console.log(res)
				            		var rest = res.data;
				            		if(rest.status == 'success'){
				            			uni.showToast({
				            				title:rest.msg,
				            				icon:'none',
				            				mask:true
				            			})
										clearInterval(lordertime);
				            			setTimeout(function() {
				            			    uni.navigateTo({
				            			    	url:'/pages/index/index'
				            			    })
				            			}, 1500)
				            		}else{
				            			uni.showToast({
				            				title:rest.msg,
				            				icon:'none',
				            				mask:true
				            			})
				            		}
				            	}
				            })
				        }
				    }
				});
			},
			toorder(){
				if(this.ma_lock == 0){
					this.jihuo()
				}else{
					clearInterval(lordertime);
					uni.navigateTo({
						url:'./orderline'
					})
				}
			},
			grabinfo(id){
				uni.navigateTo({
					url:'./orderdo?id='+id
				})
			},
			tohome(){
				clearInterval(lordertime);
				uni.navigateTo({
					url:'./index'
				})
			}
		},
		onUnload: function() {
			if(lordertime) {  
				clearInterval(lordertime);  
				lordertime = null;  
			}
		}
	}
</script>

<style>
	.is-no-order{
		text-align: center;
		margin-top:300rpx;
	}
	.no-order-ico image{
		width:180rpx;
		height: 180rpx;
	}
  .ma-box image {width:100upx;height: 100upx;}
</style>
